﻿
/*hexstudy平台上传文件使用
注:
使用者需先引用如下js文件
1.jquery.js
2.jquery-ui.js
3.jquery-fileupload.js
5.确保存在路径"Scripts/hash/crypto-min.js"和"Scripts/hash/sha1.js"
*/
(function ($) {

    //hash支持验证
    hashload();
    //参数对象

    //cms: cmsSite,
    //token: token,
    //add: function (data) {回调选择完资源},
    //done: function (result) {回调上传完成},
    //progress: function (data) {回调进度}

    //上传文件
    $.fn.hexUpload = function (options) {

        //如果为<input type="file"/>则执行
        if (this.is('input') && this.attr('type') == 'file') {
            //上传事件
            this.fileupload({
                //dataType: "xml",
                type: "POST",
                limitConcurrentUploads: 10,
                sequentialUploads: false,
                progressInterval: 100,
                //maxChunkSize: 512 * 1024,
                add: function (e, data) {
                    //data.options = options;
                    //获取上传url并提交
                    posturl(data);
                    //执行回调
                    if (options.add != undefined && options.add != 'undefined' && options.add != null)
                        Callback(data, options.add);
                },
                done: function (e, data) {
                    //获取上传结果
                    var result = getdone(data);
                },
                //进度条
                progress: function (e, data) {
                    //执行回调
                    if (options.progress != undefined && options.progress != 'undefined' && options.progress != null)
                        Callback(data, options.progress);
                },
                fail: function (e, data) {

                },
                always: function (e, data) {

                }
            })

            /*****************************************************************上传文件私有方法*/
            /*
               执行回调函数
               obj:回调函数的参数
               method:回调函数名称
            */
            var Callback = function (obj, method) {
                method(obj);
            }

            //获取上传地址并进行上传
            var posturl = function (filedata) {
                //获取上传地址
                $.ajax({
                    url: options.cms + "Upload/Index?id=" + filedata.files[0].name + "&ssotoken=" + options.token,
                    type: 'get',
                    dataType: "json",
                    success: function (result) {
                        //记录上传的服务器位置
                        filedata.utype = result.Type;
                        switch (result.Type) {
                            case '100':
                                //CommonHttp
                                uploadToHexstudy(result, filedata);
                                break;
                            case '101':
                                //FastDFS
                                uploadToHexstudy(result, filedata);
                                break;
                            case '102':
                                //OSS
                                uploadToOss(result, filedata);
                            case '103':
                                //Qiniu
                                uploadToQiniu(result, filedata);
                        }
                    }
                })
            }

            //上传成功结果
            var getdone = function (filedata) {
                var returnValue = null;
                switch (filedata.utype) {
                    case '100':
                        //CommonHttp
                        returnValue = doneToHexstudy(filedata);
                        break;
                    case '101':
                        //FastDFS
                        returnValue = doneToHexstudy(filedata);
                        break;
                    case '102':
                        //OSS
                        returnValue = doneToOss(filedata);
                    case '103':
                        //七牛
                        returnValue = doneToQiniu(filedata);
                        break;
                }
                return returnValue;
            }

            //保存到数据库(CommonHttp和FastDFS目前不需要执行)
            var saveData = function (postdata, resultdata) {

                var strJson = JSON.stringify(postdata);
                var posturl = options.cms + "FileManagement/SaveResource?id=" + strJson + "&ssotoken=" + options.token;

                $.ajax({
                    url: posturl,
                    type: 'post',
                    dataType: "json",
                    success: function (result) {

                        resultdata.result = result;
                        //执行回调
                        if (options.done != undefined && options.done != 'undefined' && options.done != null)
                            Callback(resultdata, options.done);

                        //var filename = resultdata.files[0].name;
                        //var ext = filename.substring(filename.lastIndexOf("."), filename.length).toUpperCase();

                        //if (/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(ext))
                        //{
                        //    //如果是图片类型，则切图为ipad.iphone格式(异步请求CMS)
                        //    resizeImage(result.ResourceID);
                        //}
                        return result;
                    },
                    error: function () {
                        return null;
                    }
                })
            }

            ////异步请求cms端，进行切图
            //var resizeImage = function (id) {
            //    var posturl = options.cms + "FileManagement/ResizeImage?id=" + id + "&ssotoken=" + options.token;
            //    $.ajax({
            //        url: posturl,
            //        type: 'post',
            //        dataType: "json",
            //        success: function (result) {
            //            //var temp = result;
            //            //resultdata.result = result;
            //            ////执行回调
            //            //if (options.done != undefined && options.done != 'undefined' && options.done != null)
            //            //    Callback(resultdata, options.done);

            //            //var filename = resultdata.files[0].name;
            //            //var ext = filename.substring(filename.lastIndexOf("."), filename.length).toUpperCase();

            //            //if (/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(ext)) {
            //            //    //如果是图片类型，则切图为ipad.iphone格式(异步请求CMS)
            //            //    resizeImage();
            //            //}
            //            //return result;
            //        },
            //        error: function () {
            //            //return null;
            //        }
            //    })
            //}

            //Hexstudy平台返回结果
            var doneToHexstudy = function (filedata) {

                //执行回调
                if (options.done != undefined && options.done != 'undefined' && options.done != null)
                    Callback(filedata, options.done);//Callback(filedata.result, options.done);

            }

            //OSS平台返回结果
            var doneToOss = function (filedata) {
                //获取返回值(xml->json)
                var responseData = filedata.result;
                var fileresult = Object;
                if (responseData != undefined && responseData != null && responseData.hasChildNodes()) {
                    //Oss Bucket
                    fileresult.Bucket = $(responseData.childNodes[0]).children('Bucket').text();
                    //图片下载地址
                    fileresult.Location = $(responseData.childNodes[0]).children('Location').text();
                    //bucket路径下的文件名称eg:wqrweroipoiwerwer/aa.jpg
                    fileresult.Key = $(responseData.childNodes[0]).children('Key').text();
                    //该文件的md5
                    fileresult.ETag = $(responseData.childNodes[0]).children('ETag').text();
                }

                var postjson = {
                    "MIME": filedata.files[0].type,
                    "Name": fileresult.Key,
                    "Path": fileresult.Bucket,
                    "Property": "",
                    "Size": filedata.total,
                    "UploadType": "OSS",
                    "User": null
                };
                //保存数据
                return saveData(postjson, filedata);
            }

            //七牛平台返回结果
            var doneToQiniu = function (filedata) {
                var postjson = {
                    "MIME": filedata.files[0].type,
                    "Name": filedata.result.Key,
                    "Path": filedata.result.Bucket,
                    "Property": "",
                    "Size": filedata.result.returnBody.size,
                    "UploadType": "Qiniu",
                    "User": null
                };
                //保存数据
                return saveData(postjson, filedata);
            }

            //上传到Hexstudy平台
            var uploadToHexstudy = function (info, filedata) {
                //直接提交并入库
                filedata.url = info.Url + "?ssotoken=" + options.token;
                filedata.dataType = 'json';

                //计算hash后并执行上传操作
                var btnStart = $("<input type='button' value='开始' style='display:none'/>").bind("click", function () {
                    //计算后上传
                    filedata.submit();
                })
                //hash计信息
                //var span = $("<span></span>").appendTo(filedata.context);
                handlefile(btnStart, filedata.files[0]);
            }

            //上传到OSS服务器
            var uploadToOss = function (info, filedata) {
                filedata.url = info.Url;
                filedata.dataType = 'xml';
                //处理表单数据并进行提交
                filedata.formData = {
                    Key: info.Key,
                    OSSAccessKeyId: info.OSSAccessKeyId,
                    Policy: info.Policy,
                    Signature: info.Signature,
                    Success_action_status: info.Success_action_status
                    //Type: info.Type
                };
                filedata.submit();
            }

            //上传到七牛服务器
            var uploadToQiniu = function (info, filedata) {
                filedata.url = info.Url;
                filedata.dataType = 'json';
                //处理表单数据并进行提交
                filedata.formData = {
                    key: info.Key,
                    token: info.Token
                    //Type: info.Type
                };
                filedata.submit();
            }

            /**********************************************************************************/
        }
    }


    /*************************************计算hash(hexstudy平台上传需要计算文件hash值)*/
    function hashload() {
        window.dicHash = new Array();
        if ((typeof File !== 'undefined') && !File.prototype.slice) {
            if (File.prototype.webkitSlice) {
                File.prototype.slice = File.prototype.webkitSlice;
            }

            if (File.prototype.mozSlice) {
                File.prototype.slice = File.prototype.mozSlice;
            }
        }

        if (!window.File || !window.FileReader || !window.FileList || !window.Blob || !File.prototype.slice) {
            alert("当前浏览器版本过低");
        }
    }

    function hash_file(file, workers) {
        var i, buffer_size, block, threads, reader, blob, handle_hash_block, handle_load_block;

        handle_load_block = function (event) {
            for (i = 0; i < workers.length; i += 1) {
                threads += 1;
                workers[i].postMessage({
                    'message': event.target.result,
                    'block': block
                });
            }
        };
        handle_hash_block = function (event) {
            threads -= 1;

            if (threads === 0) {
                if (block.end !== file.size) {
                    block.start += buffer_size;
                    block.end += buffer_size;

                    if (block.end > file.size) {
                        block.end = file.size;
                    }
                    reader = new FileReader();
                    reader.onload = handle_load_block;
                    blob = file.slice(block.start, block.end);

                    reader.readAsArrayBuffer(blob);
                }
            }
        };

        buffer_size = 64 * 16 * 1024;
        block = {
            'file_size': file.size,
            'start': 0
        };

        block.end = buffer_size > file.size ? file.size : buffer_size;
        threads = 0;

        for (i = 0; i < workers.length; i += 1) {
            workers[i].addEventListener('message', handle_hash_block);
        }
        reader = new FileReader();
        reader.onload = handle_load_block;
        blob = file.slice(block.start, block.end);

        reader.readAsArrayBuffer(blob);
    }

    function handle_worker_event(name, p) {
        return function (event) {
            if (event.data.result) {
                //p.next().next().text("文件分析完成，正在上传。。。");
                window.dicHash[name] = event.data.result;
                if (p) {
                    p.click();
                }

            } else {
                //p.next().next().text(正在分析文件： + (event.data.block.end * 100 / event.data.block.file_size).toFixed(2) + '%');
            }
        };
    }

    function handlefile(p, f, e) {
        event = e;
        if (event && event != null && event != undefined) {
            event.stopPropagation();
            event.preventDefault();
        }
        var file, worker;
        file = f;
        //计算sha1
        worker = new Worker('/Scripts/hash/sha1.js');
        worker.addEventListener('message', handle_worker_event(file.name, p));
        hash_file(file, [worker]);
    }

    function formatFileSize(bytes) {
        if (typeof bytes !== 'number') {
            return '';
        }
        if (bytes >= 1000000000) {
            return (bytes / 1000000000).toFixed(2) + ' GB';
        }
        if (bytes >= 1000000) {
            return (bytes / 1000000).toFixed(2) + ' MB';
        }
        if (bytes >= 1000) {
            return (bytes / 1000).toFixed(2) + ' KB';
        }
        return bytes + "B";
    }
    /**********************************************************************************/
})(jQuery);




